package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.amap.api.location.AMapLocation;
import com.badibadi.activity.ClubListActivity;
import com.badibadi.adapter.ClubOverviewZuixinAdapter_1;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.fragment.ActivityMyActivityFragment0.getFragmentData;
import com.badibadi.infos.ClubModel;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.ListsModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.AMapLocationUtils;
import com.badibadi.mytools.AMapLocationUtils.getAMapLocation;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TempTools;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.google.zxing.oned.rss.FinderPattern;
import com.libjph.util.StringUtil;
import com.miloisbadboy.view.PullToRefreshView;
import com.miloisbadboy.view.PullToRefreshView.OnFooterRefreshListener;
import com.miloisbadboy.view.PullToRefreshView.OnHeaderRefreshListener;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.test.UiThreadTest;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 俱乐部预览 main_pull_refresh_view_club
 * 
 * @author Administrator TYPE_id
 */
public class ShouYeJuLeBuFragment extends BaseFragment implements
		OnHeaderRefreshListener, OnFooterRefreshListener {
	private static final String TAG = "ClubOverview0Fragmente";
	private boolean popwindow = false;
	// private XGridView gv;
	private PullToRefreshView mPullToRefreshView;
	private GridView gv;
	private PopupWindow popup = null;
	private int Page;
	private List<ClubModel> clubModels, clubs;
	private String type;
	private ClubOverviewZuixinAdapter_1 clubOverviewZuixinAdapter_1;
	private List<ClueTypeModel> clueTypeModels;
	private ListsModel listsModel;
	private ListView type_list;
	private Popwindows_Adapter popwindows_Adapter;
	private LinearLayout fragment_club_overview0_btn_type_xgridview;
	private AutoCompleteTextView index_autocomplete_txt_view_xgridview;
	private ImageView xgridview_uppic_settings, xgridview_uppic_clean;
	private LinearLayout xgridview_search;
	private TextView xgridview_TheKeyword;

	// 查询关键字相关
	private String searchName = null;
	private String tid = null;// 活动类型id
	private String uid;// 登录用户id
	private boolean isReturnUp = true;// 按返回键是否回退关键字
	private boolean isSouSuo1 = true;
	private boolean isSouSuo2 = true;
	private Message message;
	private Bundle bundle;
	private double jingdu = 0, weidu = 0;
	private int languageType = 0;
	private MySharePreferences preferences;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case 1:
					Utils.ExitPrgress(getActivity());
					try {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_net_error));
						mPullToRefreshView.onFooterRefreshComplete();
						mPullToRefreshView.onHeaderRefreshComplete();
						if (mPullToRefreshView.getVisibility() == 0
								&& clubModels.isEmpty()) {
							mPullToRefreshView.setVisibility(View.GONE);
						}

					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 2:
					Utils.ExitPrgress(getActivity());
					try {
						clubModels.addAll(clubs);
						clubOverviewZuixinAdapter_1.notifyDataSetChanged();
						mPullToRefreshView.onFooterRefreshComplete();
						mPullToRefreshView.onHeaderRefreshComplete();
						if (mPullToRefreshView.getVisibility() == 8
								&& !clubModels.isEmpty()) {
							mPullToRefreshView.setVisibility(View.VISIBLE);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}

					//    ("跟新数据");
					break;
				case 3:
					Utils.ExitPrgress(getActivity());
					try {
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_xa10));
						mPullToRefreshView.onFooterRefreshComplete();
						mPullToRefreshView.onHeaderRefreshComplete();
						if (mPullToRefreshView.getVisibility() == 0
								&& clubModels.isEmpty()) {
							mPullToRefreshView.setVisibility(View.GONE);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 4:
					Utils.ExitPrgress(getActivity());
					try {
						if (clueTypeModels != null) {
							clueTypeModels.clear();
						}
						if (listsModel.getLists() != null
								&& !listsModel.getLists().isEmpty()) {
							for (int i = 0; i < listsModel.getLists().size(); i++) {
								ClueTypeModel clueTypeModel = new ClueTypeModel();
								clueTypeModel.setId(listsModel.getLists()
										.get(i).getId());
								clueTypeModel.setName(listsModel.getLists()
										.get(i).getName());
								clueTypeModels.add(clueTypeModel);
							}
						}
						popwindows_Adapter = new Popwindows_Adapter(
								clueTypeModels, getActivity());
						type_list.setAdapter(popwindows_Adapter);
						type_list
								.setOnItemClickListener(new OnItemClickListener() {

									@Override
									public void onItemClick(
											AdapterView<?> arg0, View view,
											int position, long arg3) {
										// TODO Auto-generated method stub
										tid = clueTypeModels.get(position)
												.getId();
										if (isSouSuo2) {
											message = new Message();
											bundle = new Bundle();
											message.what = 1;
											bundle.putString("tital_name",
													clueTypeModels
															.get(position)
															.getName());
											message.setData(bundle);
											Constants.Activity_tital_handler
													.sendMessage(message);
											isSouSuo1 = false;
											xgridview_search
													.setVisibility(View.GONE);
											Page = 1;
											clubModels.clear();
											clubOverviewZuixinAdapter_1
													.notifyDataSetChanged();
//											   
											Show_club(Page, searchName, tid,
													"2");
										} else {
											Page = 1;
											isSouSuo1 = false;
											xgridview_TheKeyword
													.setVisibility(View.VISIBLE);
											xgridview_search
													.setVisibility(View.GONE);
											xgridview_TheKeyword
													.setText(clueTypeModels
															.get(position)
															.getName());
											xgridview_search
													.setVisibility(View.GONE);
											clubModels.clear();
											clubOverviewZuixinAdapter_1
													.notifyDataSetChanged();
//											   
											Show_club(Page, searchName, tid,
													"2");
										}
										if (popup != null) {
											popup.dismiss();
										}
									}
								});
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 5:
					if (tid != null) {
						isSouSuo1 = false;
						xgridview_search.setVisibility(View.GONE);
						Page = 1;
						clubModels.clear();
						clubOverviewZuixinAdapter_1.notifyDataSetChanged();

					} else {
						// Show_club(Page, searchName, tid, "2");
					}
					break;
				default:
					break;
				}
			} catch (Exception e) {
				   
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		clubModels = new ArrayList<ClubModel>();

	}// regionhomepage_import_layout2

	@Override
	public View onCreateView(final LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		final View view = inflater.inflate(R.layout.xgridview_club, null);
		try {
			tid = getArguments().getString("TYPE_id");
			type = getArguments().getString("type");
			//    
		} catch (Exception e) {
			// TODO: handle exception
		}
		preferences = new MySharePreferences(getActivity(), "language");
		languageType = preferences.get("language", 0);
		clubOverviewZuixinAdapter_1 = new ClubOverviewZuixinAdapter_1(
				getActivity(), clubModels, type, weidu, jingdu);
		uid = Utils.getUid(getActivity());
		

		Page = 1;
		clueTypeModels = new ArrayList<ClueTypeModel>();
		mPullToRefreshView = (PullToRefreshView) view
				.findViewById(R.id.main_pull_refresh_view_club_area);
		xgridview_TheKeyword = (TextView) view
				.findViewById(R.id.xgridview_TheKeyword);
		xgridview_uppic_clean = (ImageView) view
				.findViewById(R.id.xgridview_uppic_clean);
		gv = (GridView) view.findViewById(R.id.xgridView11_club);
		gv.setNumColumns(2);
		gv.setPadding(0, DisplayUtil.dip2px(getActivity(), 10),
				DisplayUtil.dip2px(getActivity(), 10),
				DisplayUtil.dip2px(getActivity(), 10));
		gv.setAdapter(clubOverviewZuixinAdapter_1);
		xgridview_search = (LinearLayout) view
				.findViewById(R.id.xgridview_search);
		xgridview_search.setVisibility(View.GONE);
		fragment_club_overview0_btn_type_xgridview = (LinearLayout) view
				.findViewById(R.id.fragment_club_overview0_btn_type_xgridview);
		index_autocomplete_txt_view_xgridview = (AutoCompleteTextView) view
				.findViewById(R.id.index_autocomplete_txt_view_xgridview);
		xgridview_uppic_settings = (ImageView) view
				.findViewById(R.id.xgridview_uppic_settings);
		InitPop(fragment_club_overview0_btn_type_xgridview);
		xgridview_uppic_clean.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				index_autocomplete_txt_view_xgridview.setText("");
			}
		});
		if (type.equals("nearby")) {
			if (tid != null) {
				isSouSuo1 = false;
				xgridview_search.setVisibility(View.GONE);
				Page = 1;
				clubModels.clear();
				clubOverviewZuixinAdapter_1.notifyDataSetChanged();

			} else {
				// Show_club(Page, searchName, tid, "2");
			}
			dingwei();
			//    
		}
		if (!type.equals("nearby")) {
			if (tid != null) {
				isSouSuo1 = false;
				xgridview_search.setVisibility(View.GONE);
				Page = 1;
				clubModels.clear();
				clubOverviewZuixinAdapter_1.notifyDataSetChanged();
				Show_club(Page, searchName, tid, "2");
			} else {
				Show_club(Page, searchName, tid, "2");
			}
		}
//		   
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		return view;
	}

	private void InitPop(final View v) {
		fragment_club_overview0_btn_type_xgridview
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						OpenOrClosePopWindows(v);
					}
				});
		xgridview_uppic_settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (isSouSuo1) {
					searchName = index_autocomplete_txt_view_xgridview
							.getText().toString().trim();
					message = new Message();
					bundle = new Bundle();
					message.what = 1;
					isSouSuo2 = false;
					bundle.putString("tital_name", "“" + searchName + "”");
					message.setData(bundle);
					Constants.Activity_tital_handler.sendMessage(message);
					Page = 1;
					clubModels.clear();
					clubOverviewZuixinAdapter_1.notifyDataSetChanged();
//					   
					Show_club(Page, searchName, tid, "2");
				} else {

				}
			}
		});
	}

	/**
	 * 打开或管理悬浮对话框
	 * 
	 * @param inflater
	 * @param v
	 */
	public void OpenOrClosePopWindows(View v) {

		LayoutInflater inflater = LayoutInflater.from(getActivity());
		View root = inflater.inflate(
				R.layout.fragment_club_overview_popwindows, null);
		type_list = (ListView) root.findViewById(R.id.type_list);
		popup = new PopupWindow(root, LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.setFocusable(true);
		popup.setTouchable(true);
		popup.setOutsideTouchable(true);
		Ahow_Type_Clue();
		popup.showAsDropDown(v);
	}

	private void Ahow_Type_Clue() {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				listsModel = new ListsModel();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", "julebu");
				map.put("languageType", TempTools.BackLanguage(languageType));
//				   
				String cluecontent = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "type/listType");
				if (cluecontent != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							cluecontent);
//					   
					if (results != null && results.getRetmsg() != null) {
						try {
							//    (results.getRetmsg());
							listsModel = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), ListsModel.class);
							handler.sendEmptyMessage(4);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void Show_club(final int page, final String key, final String tid,
			final String distance) {
		// Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				clubs = new ArrayList<ClubModel>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", type);
				map.put("uid", uid);
				map.put("page", page);
				map.put("pageNum", 10);
				if (key != null) {
					map.put("key", key);
				}
				if (tid != null) {
					map.put("tid", tid);
				}
				if (type.equals("nearby")) {
					try {
						map.put("arr", fengzhuang_jingweidu());
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						   
					}
				}
				map.put("distance", distance);
//				   (map.toString());
				String content = Utils.sendRequest(map,
						com.badibadi.mytools.Constants.BadiUrl_1
								+ "club/show_club");
				System.out.println("julebu"+content);
				if (content != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    ("俱乐部总览返回数据是:" +
						// results.getRetmsg());
//						   
						try {
							clubs = JSONUtils.getListByJsonString(
									results.getRetmsg(), ClubModel.class);
							System.out.println("juleburesults"+results.getRetmsg());
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						if (Page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						handler.sendEmptyMessage(3);
					}
				} else {
					if (Page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private JSONObject fengzhuang_jingweidu() throws JSONException {
		JSONObject object = new JSONObject();
		object.put("map_y", jingdu);// jingdu
		object.put("map_x", weidu);// weidu
		return object;
	}

	// /**
	// * 打开或管理悬浮对话框
	// *
	// * @param inflater
	// * @param v
	// */
	// public void OpenOrClosePopWindows(LayoutInflater inflater, View v) {
	// if (popup == null) {
	// View root = inflater.inflate(
	// R.layout.fragment_club_overview_popwindows, null);
	// popup = new PopupWindow(root, 300, 360);
	// popup.showAsDropDown(v);
	// } else {
	// popup.dismiss();
	// popup = null;
	// }
	// }
	// @Override
	// public void OnLoadMore() {
	// Show_club(++Page);
	// }
	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		// TODO Auto-generated method stub
//		   
		Show_club(++Page, searchName, tid, "2");
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		Page = 1;
		if (clubModels != null) {
			clubModels.clear();
		}
//		   
		Show_club(Page, searchName, tid, "2");
	}

	/**
	 * 点击回退键之后的操作回退到上一级
	 * 
	 * @param get
	 */
	public void getSearchIsReturnUp_2(getFragmentData_2 get) {
		get.getIsReturnUp_2(isReturnUp);
		if (xgridview_search.getVisibility() == 8) {
			isSouSuo1 = true;
			tid = null;
			xgridview_search.setVisibility(View.VISIBLE);
			xgridview_TheKeyword.setVisibility(View.GONE);
			if (isSouSuo2) {
				message = new Message();
				bundle = new Bundle();
				message.what = 1;
				bundle.putString("tital_name",
						getResources().getString(R.string.l_xb51));
				message.setData(bundle);
				Constants.Activity_tital_handler.sendMessage(message);
				Page = 1;
				clubModels.clear();
				clubOverviewZuixinAdapter_1.notifyDataSetChanged();
//				   
				Show_club(Page, searchName, tid, "2");
			}
		} else if (xgridview_search.getVisibility() == 0 && searchName != null) {
			isSouSuo2 = true;
			searchName = null;
			message = new Message();
			bundle = new Bundle();
			message.what = 1;
			bundle.putString("tital_name",
					getResources().getString(R.string.l_xb51));
			message.setData(bundle);
			Constants.Activity_tital_handler.sendMessage(message);
			Page = 1;
			clubModels.clear();
			clubOverviewZuixinAdapter_1.notifyDataSetChanged();
//			   
			Show_club(Page, searchName, tid, "2");
		} else {
			((getActivity())).finish();
			getActivity().overridePendingTransition(R.anim.slide_left2,
					R.anim.slide_right2);
		}
	}

	public interface getFragmentData_2 {
		// 是否返回到上一级returnSearch
		void getIsReturnUp_2(boolean isReturn);
	}

	private void dingwei() {
		// 这只是一个使用接口的模板
		final AMapLocationUtils aMapLocationUtils = new AMapLocationUtils(
				getActivity());
		new Thread(new Runnable() {
			boolean isRun = true;

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isRun) {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						   
					}
					aMapLocationUtils
							.setOnAMapLocationClistener(new getAMapLocation() {

								@Override
								public void getAMapLocation(
										AMapLocation aMapLocation) {
									// TODO Auto-generated method stub
									//    
									if (aMapLocation != null) {
										//    
										// "经度-》"+aMapLocation.getLongitude()+"纬度=》"+aMapLocation.getLatitude());
//										   ("经度:"
//												+ aMapLocation.getLongitude()
//												+ "纬度:"
//												+ aMapLocation.getLatitude());
										jingdu = aMapLocation.getLongitude();
										weidu = aMapLocation.getLatitude();
										clubOverviewZuixinAdapter_1
												.setMap_x(weidu);
										clubOverviewZuixinAdapter_1
												.setMap_y(jingdu);
//										   
										Show_club(Page, searchName, tid, "2");
										isRun = false;
										aMapLocationUtils.stopLocation();
									}
								}
							});
				}
			}
		}).start();
	}
}
